<?php

namespace app\admin\controller;

use think\Db;
use app\admin\model\Admin as AdminModel;
use app\admin\model\AuthGroup;

class Admin extends Backend
{

    /**
     * @var string
     * 快速搜索的时候查询的字段，支持逗号分隔的字符串或数组
     */
    protected $searchFields = 'id,username,nickname,mobile,email';

    /**
     * @var array
     * 不需要权限认证的控制器/方法（*表示该控制器的所有方法都不需要权限认证）
     */
    protected $noNeedAuth = ['setting', 'action_log'];

    /**
     * 我的操作日志
     *
     * @return void
     */
    public function action_log()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $page, $offset, $limit) = $this->buildSearchParams($this->searchFields);
            $rows = Db::name('admin_log')->alias('a')->join('__ADMIN__ b', 'a.admin_id=b.id')->where('a.admin_id', $this->auth->id)->where($where)->field('a.*,b.username')->order($sort, $order)->paginate([
                'list_rows' => $limit,
                'page' => $page,
            ]);
            $data = [
                'total' => $rows->total(),
                'rows' => $rows->items(),
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * 我的日志的详情
     *
     * @return void
     */
    public function action_log_detail(){
        $this->modelName = 'AdminLog';
        return parent::detail();
    }

    /**
     * 列表页
     *
     * @return void
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $page, $offset, $limit) = $this->buildSearchParams($this->searchFields);
            $rows = Db::name($this->tableName)->alias('a')->leftJoin('__AUTH_GROUP_ACCESS__ b', 'a.id=b.uid')->leftJoin('__AUTH_GROUP__ c', 'b.group_id=c.id')->where($where)->order('a.' . $sort, $order)->field('a.*,group_concat(c.title) as groups_name')->group('a.id')->paginate([
                'list_rows' => $limit,
                'page' => $page,
            ]);
            $data = [
                'total' => $rows->total(),
                'rows' => $rows->items(),
            ];

            return json($data);
        }

        //查询所有的用户组
        $groups = \app\admin\model\AuthGroup::getAllNormalGroupsTree();
        $this->assign('groups', $groups);
        $group_id = input('param.group_id/d', 0);
        $this->assign('group_id', $group_id);

        return $this->fetch();
    }

    /**
     * 个人设置
     * Author: LCY<409028735@qq.com>
     * Time: 2021/12/25 22:48
     * Note:
     */
    public function setting()
    {
        if ($this->request->isPost()) {
            //获取提交的数据
            $data = input('post.');
            //验证token

            if (isset($data['password']) && empty($data['password'])) {
                unset($data['password']);
            }

            //表单验证
            $this->validate_response($data, $this->modelName . '.setting');
            try {
                $res = model('Admin')->allowField(true)->isUpdate(true)->save($data);
            } catch (\Exception $e) {
                $this->error('设置失败：' . $e->getMessage());
            }

            if (false === $res) {
                $this->error('设置失败，请重试');
            }
            $this->auth->updateUserInfoSession();
            $this->request->hasWriteLog = true;
            $this->success('设置完成');
        }

        $info = $this->auth->getUserInfo();
        if (empty($info)) {
            $this->error('用户信息不存在');
        }
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 添加管理员
     * @return mixed
     * Author: LCY<409028735@qq.com>
     * Time: 2021/12/25 21:10
     * Note:
     */
    public function add()
    {
        if ($this->request->isPost()) {
            //获取提交的数据
            $data = input('post.');
            //验证token

            //表单验证
            $this->validate_response($data, $this->modelName . '.add');

            //保存到数据库
            try {
                $res = AdminModel::create($data);
            } catch (\Exception $e) {
                $this->error('添加失败：' . $e->getMessage());
            }

            if (!$res) {
                $this->error('添加失败，请重试');
            }

            //保存管理员组别
            $datas = [];
            $group_ids = $data['group_ids'];
            foreach ($group_ids as $gid) {
                $datas[] = [
                    'uid' => $res->id,
                    'group_id' => $gid
                ];
            }
            if (!empty($datas)) {
                try {
                    Db::name('auth_group_access')->insertAll($datas);
                } catch (\Exception $e) {
                }
            }

            $this->success('添加完成');
        }

        $groups = \app\admin\model\AuthGroup::getAllNormalGroupsTree();
        $this->assign('groups', $groups);

        return $this->fetch();
    }

    /**
     * 修改管理员
     * @return mixed
     * Author: LCY<409028735@qq.com>
     * Time: 2021/12/25 21:11
     * Note:
     */
    public function edit()
    {
        $id = input('id/d', 0);
        if (config('auth.super_admin_id') == $id) {
            $this->error('超级管理员不能修改');
        }

        $info = AdminModel::get($id);
        if (empty($info)) {
            $this->error('信息不存在');
        }

        if ($this->request->isPost()) {
            //获取提交的数据
            $data = input('post.');
            if (isset($data['password']) && empty($data['password'])) {
                unset($data['password']);
            }
            //验证token

            //表单验证
            $this->validate_response($data, $this->modelName . '.edit');

            //保存到数据库
            try {
                $res = $info->allowField(true)->isUpdate(true)->save($data);
            } catch (\Exception $e) {
                $this->error('修改失败：' . $e->getMessage());
            }

            if (false === $res) {
                $this->error('修改失败，请重试');
            }

            //保存所属的权限组，先删除原有的权限组，再保存现有的权限组
            Db::name('auth_group_access')->where('uid', $id)->delete();
            $datas = [];
            $group_ids = $data['group_ids'];
            foreach ($group_ids as $gid) {
                $datas[] = [
                    'uid' => $info->id,
                    'group_id' => $gid
                ];
            }
            if (!empty($datas)) {
                try {
                    Db::name('auth_group_access')->insertAll($datas);
                } catch (\Exception $e) {
                }
            }

            $this->success('修改完成');
        }



        if (empty($info)) {
            $this->error('数据不存在');
        }

        $this->assign('info', $info);

        $groups = \app\admin\model\AuthGroup::getAllNormalGroupsTree();
        $this->assign('groups', $groups);

        //查询用户所属的权限组
        $group_ids = Db::name('auth_group_access')->where('uid', $id)->column('group_id');
        $this->assign('group_ids', $group_ids ?: []);
        return $this->fetch();
    }

    /**
     * 删除用户
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * Author: LCY<409028735@qq.com>
     * Time: 2021/12/25 22:30
     * Note:
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $ids = input('ids/s', '');
            if (empty($ids)) {
                $this->error('还未选择要删除的数据');
            }
            if (in_array(config('auth.super_admin_id'), explode(',', $ids))) {
                $this->error('ID为' . config('auth.super_admin_id') . '的超级管理员不能删除');
            }

            try {
                $res = model($this->modelName)->where('id', 'in', $ids)->delete();
            } catch (\Exception $e) {
                $this->error('修改失败：' . $e->getMessage());
            }

            if (!$res) {
                $this->error('删除失败，请重试');
            }

            //删除用户所属的权限组
            Db::name('auth_group_access')->where('uid', 'in', $ids)->delete();

            $this->success('删除完成');
        }
    }
}
